import wifi from '@ohos.wifi';
import socket from '@ohos.net.socket';
export default {
    data: {
        title: "",
        localip:"192.168.43.103",
        tcp:socket.constructTCPSocketInstance(),
        TAG:"YZJ ",
        remoteip:"192.168.1.113",
    },
    onInit() {
        this.title = "Hello World";
        this.getIpAddress();
        this.creatScoket();
    },
    getIP(e){
        this.remoteip=e.value()
    },
    async creatScoket(){
        var that = this;
        this.getIpAddress();
        this.tcp.bind({address:this.localip, port:8080, family: 1}, err => {
            if (err) {
                console.info(this.TAG+'bind fail');
                this.title='bind fail'
                return;
            }
            this.title='bind success'
            console.info(this.TAG+'bind success');
        })
        this.tcp.on('message', value => {
            let buffer = value.message;
            let dataView = new DataView(buffer);
            let str = "";

            for (let i = 0;i < dataView.byteLength; ++i) {
                str += String.fromCharCode(dataView.getUint8(i))

            }

            console.info(this.TAG+"on connect recevied"+str );





        });
    },
    async sendMessage(){

        let promise = this.tcp.connect({ address: {address: this.remoteip, port: 8080, family: 1} , timeout: 6000});
        promise.then(() => {
            console.log(this.TAG+'connect success');
            this.tcp.send({
                data:'101->102->103'
            },err => {
                if (err) {
                    console.log(this.TAG+'send fail');
                    return;
                }
                console.log(this.TAG+'send success');
            })
        }).catch(err => {
            console.log(this.TAG+'connect fail');
        });
    },
    getIpAddress(){
        let ip=wifi.getIpInfo().ipAddress;
        this.localip = (ip >> 24 & 0xFF)+"."+ ((ip >> 16) & 0xFF)+"."+((ip >> 8) & 0xFF)+"."+(ip & 0xFF);
        console.info(this.TAG+this.localip);
    },
}
